﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using Kimgwajang.MidnightPeach.Utilities;
using Kimgwajang.MidnightPeach.Properties;
using System.Linq;
using Kimgwajang.MidnightPeach.Schema;
using System.Diagnostics;
using System.IO;
using System.Threading;

namespace Kimgwajang.MidnightPeach.Forms
{
    public partial class LoadForm : Form
    {
        public LoadForm()
        {
            InitializeComponent();
        }

        private readonly HistoryQueue _dbmlQueue = new HistoryQueue();
        private readonly HistoryQueue _packageQueue = new HistoryQueue();

        private string _createdDbmlFileName;

        public string DbmlPath
        {
            get
            {
                if (rdbUseExistingDbml.Checked)
                    return cbbDbml.Text;
                else
                    return _createdDbmlFileName;
            }
        }

        public string PackagePath
        {
            get
            {
                if (rdbBuiltInPackage.Checked)
                    return ((PackageFileInfo) cbbBuiltInPackage.SelectedItem).Path;
                else
                    return cbbCustomPackage.Text;
            }
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            _dbmlQueue.Enqueued += DbmlQueue_Queued;
            _dbmlQueue.Load(Settings.Default.DbmlHistory);
            cbbDbml.Text = _dbmlQueue.LastItem;

            _packageQueue.Enqueued += PackageQueue_Queued;
            _packageQueue.Load(Settings.Default.PackageHistory);
            cbbCustomPackage.Text = _packageQueue.LastItem;

            ofdDbml.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            ofdPackage.InitialDirectory = Environment.CurrentDirectory;

            var dbmlFiles = Utility.GetPackageFiles();
            foreach (var dbmlFile in dbmlFiles)
                cbbBuiltInPackage.Items.Add(dbmlFile);

            if (cbbBuiltInPackage.Items.Count > 0)
                cbbBuiltInPackage.SelectedIndex = 0;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            _dbmlQueue.Enqueue(DbmlPath);
            _packageQueue.Enqueue(PackagePath);

            Settings.Default.DbmlHistory = _dbmlQueue.ToString();
            Settings.Default.PackageHistory = _packageQueue.ToString();
            Settings.Default.Save();

            base.OnClosing(e);
        }

        private void DbmlQueue_Queued(object sender, HistoryQueue.EnqueuedEventArgs e)
        {
            cbbDbml.Items.Clear();
            cbbDbml.Items.AddRange(e.Histories);
        }

        private void PackageQueue_Queued(object sender, HistoryQueue.EnqueuedEventArgs e)
        {
            cbbCustomPackage.Items.Clear();
            cbbCustomPackage.Items.AddRange(e.Histories);
        }

        private void btnDbmlBrowse_Click(object sender, EventArgs e)
        {
            if (ofdDbml.ShowDialog() == DialogResult.OK)
                cbbDbml.Text = ofdDbml.FileName;
        }

        private void btnPackageBrowse_Click(object sender, EventArgs e)
        {
            if (ofdPackage.ShowDialog() == DialogResult.OK)
                cbbCustomPackage.Text = ofdPackage.FileName;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (rdbCreateNewDbml.Checked)
            {
                if (CreateDbmlFile(txtConnectionString.Text, txtDataContextName.Text, txtNamespace.Text) == false)
                {
                    MessageBox.Show(Resources.FailedToCreateDbml);
                    return;
                }
            }

            DialogResult = DialogResult.OK;
                Close();
        }

        private void ToggleDbmlPanels(object sender, EventArgs e)
        {
            grbUseExistingDbml.Enabled = rdbUseExistingDbml.Checked;
            grbCreateNewDbml.Enabled = rdbCreateNewDbml.Checked;

            #region 위 grbCreateNewDbml.Enabled = rdbCreateNewDbml.Checked 문장이 알 수 없는 이유로 실행되지 않음
            btnPathOfSqlMetal.Enabled = rdbCreateNewDbml.Checked;
            #endregion

        }

        private void TogglePackagePanels(object sender, EventArgs e)
        {
            grbBuiltInPackage.Enabled = rdbBuiltInPackage.Checked;
            grbCustomPackage.Enabled = rdbCustomPackage.Checked;

            #region 위 grbCustomPackage.Enabled = rdbCustomPackage.Checked 문장이 알 수 없는 이유로 실행되지 않음
            cbbCustomPackage.Enabled = rdbCustomPackage.Checked;
            btnPackageBrowse.Enabled = rdbCustomPackage.Checked;
            #endregion
        }

        private bool CreateDbmlFile(string connectionStirng, string dataContextName, string @namespace)
        {
            try
            {
                _createdDbmlFileName = Guid.NewGuid().ToString("N") + ".dbml";

                string argument = string.Format(@" /conn:""{0}"" /context:{1} /namespace:{2} /dbml:""{3}""", connectionStirng, dataContextName, @namespace, _createdDbmlFileName);

                var process = Process.Start(txtPathOfSqlMetal.Text, argument);
                process.WaitForExit();

                return File.Exists(_createdDbmlFileName);
            }
            catch
            {
                return false;
            }
        }

        private void btnPathOfSqlMetal_Click(object sender, EventArgs e)
        {
            if (ofdPathOfSqlMetal.ShowDialog() == DialogResult.OK)
                txtPathOfSqlMetal.Text = ofdPathOfSqlMetal.FileName;
        }
    }
}